package com.nuanqian.springbootdubboclient.acitivemq;

import org.apache.activemq.command.ActiveMQObjectMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.List;
import java.util.Map;

/**
 * MQ消息监听
 * @author 李蒙
 * @date 2020/7/7 13:54
 */


@Component
public class ConsumerListener{
    private final Logger logger = LoggerFactory.getLogger(ConsumerListener.class);

    //topic模式的消费者
//    @JmsListener(destination="${spring.activemq.topic-name}", containerFactory="topicListener")
//    public void readActiveQueue(String list) {
//
//        logger.info("topic接受到：" +list);
//    }


    //topic模式的消费者
    /**
     * ObjectMessage对象取决于Java编组/非编组对象有效负载的序列化。通常认为此过程是不安全的 需配置信任白名单
     * @param obj
     * @throws JMSException
     */
    @JmsListener(destination="${spring.activemq.topic-name}", containerFactory="topicListener")
    public void readActiveQueue(Object obj) throws  JMSException{
        ActiveMQObjectMessage message = (ActiveMQObjectMessage) obj;
//        message.setTrustedPackages();//信任哪些包  未测试
        message.setTrustAllPackages(true);//信任所有
        List<Map> list= (List<Map>)message.getObject();
        logger.info("OBJMESSAGE:"+list);
    }

    //queue模式的消费者
    @JmsListener(destination = "${spring.activemq.queue-name}",containerFactory = "queueListener")
    public void receiveQueue(TextMessage message, Session session) throws JMSException {
        logger.info("consumer2收到queue_string信息:{}",message.getText());
        try {
//            int a = 1 / 0;
            //业务处理结束，手动ack通知队列收到消息，可以把消息从队列移除
            message.acknowledge();
        } catch (Exception e) {
            logger.error(e.getMessage());
            /**
             * 通知队列重发，默认每秒重发1次，一共重发6次，
             * 若想自定义重试次数，重试间隔时间可以设置
             * ActiveMQConnectionFactory的RedeliveryPolicyMap的RedeliveryPolicy
             */
            session.recover();
        }
    }

}
